package cn.mst.vrs.service.user;

import cn.hutool.core.util.ObjUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.mst.vrs.controller.admin.user.vo.UserPageReqVO;
import cn.mst.vrs.controller.admin.user.vo.UserSaveReqVO;
import cn.mst.vrs.controller.app.user.vo.VrsUserPrivateRespVO;
import cn.mst.vrs.convert.VrsUserConvert;
import cn.mst.vrs.dal.dataobject.auth.AuthDO;
import cn.mst.vrs.dal.dataobject.user.UserDO;
import cn.mst.vrs.dal.mysql.auth.VrsAuthMapper;
import cn.mst.vrs.dal.mysql.user.VrsUserMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.mst.vrs.enums.ErrorCodeConstants.AUTH_NOT_EXISTS;
import static cn.mst.vrs.enums.ErrorCodeConstants.USER_NOT_EXISTS;

/**
 * 预约用户 Service 实现类
 *
 * @author 超级管理员
 */
@Service
@Validated
public class UserServiceImpl implements UserService {

    @Resource
    private VrsUserMapper vrsUserMapper;

    @Resource
    private VrsAuthMapper vrsAuthMapper;

    @Override
    public Long createUser(UserSaveReqVO createReqVO) {
        // 插入
        UserDO user = BeanUtils.toBean(createReqVO, UserDO.class);
        vrsUserMapper.insert(user);
        // 返回
        return user.getId();
    }

    @Override
    public void updateUser(UserSaveReqVO updateReqVO) {
        // 校验存在
        validateUserExists(updateReqVO.getId());
        // 更新
        UserDO updateObj = BeanUtils.toBean(updateReqVO, UserDO.class);
        vrsUserMapper.updateById(updateObj);
    }

    @Override
    public void deleteUser(Long id) {
        // 校验存在
        validateUserExists(id);
        // 删除
        vrsUserMapper.deleteById(id);
    }

    private void validateUserExists(Long id) {
        if (vrsUserMapper.selectById(id) == null) {
            throw exception(USER_NOT_EXISTS);
        }
    }

    @Override
    public UserDO getUser(Long id) {
        return vrsUserMapper.selectById(id);
    }

    @Override
    public PageResult<UserDO> getUserPage(UserPageReqVO pageReqVO) {
        return vrsUserMapper.selectPage(pageReqVO);
    }

    @Override
    public VrsUserPrivateRespVO getPrivateInfo(Long authId) {
        AuthDO authDO = vrsAuthMapper.selectById(authId);
        if (ObjUtil.isNull(authDO)){
            throw exception(AUTH_NOT_EXISTS);
        }
        return VrsUserConvert.INSTANCE.toPrivateRespVO(vrsUserMapper.selectById(authDO.getUserId()));
    }

}